import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import QuestionBank from '../views/QuestionBank.vue'
import ProfilePage from '../views/ProfilePage.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册' }
  },
  {
    path: '/stockAnalysis',
    name: 'StockAnalysis',
    component: () => import('@/views/StockAnalysis.vue'),
    meta: { title: '股票分析', requireAuth: true }
  },
  {
    path: '/stock',
    name: 'StockList',
    component: () => import('@/components/stock/StockList.vue'),
    meta: { requireAuth: true }
  },
  {
    path: '/stock/:id',
    name: 'StockDetail',
    component: () => import('@/components/stock/StockDetail.vue'),
    meta: { requireAuth: true }
  },
  {
    path: '/my-stock',
    name: 'MyStockList',
    component: () => import('@/components/stock/MyStockList.vue'),
    meta: { requireAuth: true }
  },
  {
    path: '/user-manage',
    name: 'UserManage',
    component: () => import('@/views/UserManage.vue'),
    meta: { requiresAuth: true, title: '用户管理' }
  },
  {
    path: '/role-manage',
    name: 'RoleManage',
    component: () => import('@/views/RoleManage.vue'),
    meta: { requiresAuth: true, title: '角色管理' }
  },
  {
    path: '/menu-manage',
    name: 'MenuManage',
    component: () => import('@/views/MenuManage.vue'),
    meta: { requiresAuth: true, title: '菜单管理' }
  },
  {
    path: '/',
    name: 'HomePage',
    component: () => import('@/views/HomePage.vue'),
    meta: { title: '新首页', requireAuth: true }
  },
  {
    path: '/question-bank',
    name: 'QuestionBank',
    component: QuestionBank,
  },
  {
    path: '/practice',
    name: 'PracticePage',
    component: () => import('../views/Practice.vue'),
  },
  {
    path: '/profile',
    name: 'ProfilePage',
    component: ProfilePage,
  },
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title || 'Vue App'

  const isLoggedIn = store.getters['user/isLoggedIn']
  const requiresAuth = to.matched.some(record => record.meta.requireAuth)
  const hasToken = store.state.user.token

  // 如果已登录且访问登录/注册页，重定向到首页
  if (isLoggedIn && (to.path === '/login' || to.path === '/register')) {
    next({ path: '/' })
    return
  }

  // 如果有token但没有用户信息，尝试获取用户信息
  if (hasToken && !store.state.user.userInfo) {
    try {
      await store.dispatch('user/getUserInfo')
      next({ ...to, replace: true })
    } catch (error) {
      console.error('获取用户信息失败:', error)
      store.dispatch('user/logout')
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
    return
  }

  // 如果需要认证
  if (requiresAuth) {
    if (!isLoggedIn) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return
    }
  }

  next()
})

export default router